<template>
  <div class="patient-list-page">
    <div class="toolbar">
      <el-button type="primary" @click="openAddModal">添加患者</el-button>
      <el-button @click="handleExport">导出患者数据</el-button>
      <el-input v-model="searchRealName" placeholder="搜索真实姓名" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch" style="width:180px;" />
      <el-input v-model="searchPhone" placeholder="搜索手机号" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch" style="width:180px; margin-left:8px;" />
      <el-button type="primary" @click="handleSearch" style="margin-left:8px;">搜索</el-button>
    </div>
    <el-table :data="pagedPatients" style="width: 100%" border @selection-change="handleSelectionChange"
      :row-key="row => row.id" :empty-text="'暂无数据'">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column label="性别" width="80">
        <template #default="{ row }">
          <el-tag v-if="Number(row.gender) === 1" type="primary">男</el-tag>
          <el-tag v-else-if="Number(row.gender) === 0" type="danger">女</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="80">
        <template #default="{ row }">
          <span>{{ getAge(row.birthDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="140">
        <template #default="{ row }">
          <span>{{ row.phone || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="idCard" label="身份证号" width="180">
        <template #default="{ row }">
          <span>{{ row.idCard || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址">
        <template #default="{ row }">
          <span>{{ row.address || '-' }}</span>
        </template>
      </el-table-column>
      <!--
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <span style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="val => handleStatusChange(row, val)"
              size="small"
            />
            <el-tag v-if="row.status === 1" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="row.status === 0" type="info" size="small">禁用</el-tag>
            <span v-else>-</span>
          </span>
        </template>
      </el-table-column>
      -->
      <el-table-column prop="createTime" label="创建时间" width="170">
        <template #default="{ row }">
          <span>{{ row.createTime ? row.createTime.replace('T', ' ') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="170">
        <template #default="{ row }">
          <span>{{ row.updateTime ? row.updateTime.replace('T', ' ') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openEditModal(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="goDetail(row)">详情</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="filteredPatients.length"
        :page-size="pageSize" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 统一的添加/编辑模态框 -->
    <el-dialog :title="modalTitle" v-model="modalVisible" width="500px" @close="resetModal">
      <el-form :model="modalForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="modalForm.realName" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="modalForm.gender" placeholder="请选择">
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="modalForm.birthDate" type="date" placeholder="请选择出生日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="modalForm.phone" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="modalForm.idCard" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="modalForm.address" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="modalForm.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="handleModalOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { addPatientApi, updatePatientApi, getPatientPageApi, deletePatientApi, exportPatientApi } from '@/api/patient'
import { downloadBlobFile } from '@/utils/request'

interface Patient {
  id: number | string
  username?: string
  realName: string
  gender: number | string
  birthDate?: string
  phone?: string
  idCard?: string
  address?: string
  status?: number
  createTime?: string
  updateTime?: string
}

const params = ref({
  page: 1,
  pageSize: 10,
  search: ''
})

const patients = ref<Patient[]>([
])
onMounted(async () => {
  try {
    const res = await getPatientPageApi(params.value)
    if (res && res.data && res.data.records) {
      patients.value = res.data.records
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
})
const searchRealName = ref('')
const searchPhone = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selected = ref<Patient[]>([])

const modalVisible = ref(false)
const modalForm = ref<any>({})
const editingId = ref<number | null>(null)
const modalTitle = computed(() => editingId.value ? '编辑患者' : '添加患者')

const filteredPatients = computed(() => {
  if (!searchRealName.value && !searchPhone.value) return patients.value
  const sRealName = searchRealName.value.trim().toLowerCase()
  const sPhone = searchPhone.value.trim().toLowerCase()
  return patients.value.filter((p: Patient) =>
    (p.realName && p.realName.includes(sRealName)) ||
    (p.phone && p.phone.includes(sPhone))
  )
})
const pagedPatients = computed(() => {
  // 直接返回全部patients，分页交给el-pagination
  return patients.value
})
const router = useRouter()

async function handleSearch() {
  params.value.page = 1
  try {
    const res = await getPatientPageApi({
      page: currentPage.value,
      pageSize: pageSize.value,
      realName: searchRealName.value.trim(),
      phone: searchPhone.value.trim()
    })
    if (res && res.data && res.data.records) {
      patients.value = res.data.records
    }
  } catch (e) {
    ElMessage.error('搜索失败')
  }
}
function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}
function handleCurrentChange(page: number) {
  currentPage.value = page
}
function handleSelectionChange(val: Patient[]) {
  selected.value = val
}
function openAddModal() {
  editingId.value = null
  modalForm.value = { realName: '', gender: '', birthDate: '', phone: '', idCard: '', address: '', status: 1 }
  modalVisible.value = true
}
function openEditModal(row: Patient) {
  editingId.value = row.id
  modalForm.value = { ...row, gender: row.gender !== undefined ? String(row.gender) : '' }
  modalVisible.value = true
}
async function handleModalOk() {
  if (!modalForm.value.realName || !modalForm.value.gender || !modalForm.value.phone) {
    ElMessage.warning('请填写姓名、性别和手机号')
    return
  }
  if (editingId.value) {
    // 编辑
    const res = await updatePatientApi({
      id: editingId.value,
      ...modalForm.value
    });
    if (res && res.code === 200) {
      const index = patients.value.findIndex((p: Patient) => p.id === editingId.value);
      if (index !== -1) {
        patients.value[index] = { ...modalForm.value } as Patient;
      }
      ElMessage.success('更新成功');
    } else {
      ElMessage.error(res?.msg || '更新失败');
    }
  } else {
    // 添加
    const res = await addPatientApi({ ...modalForm.value })
    if (res && res.data && res.data.code === 200) {
      const newPatient = {
          ...modalForm.value
        } as Patient;
        patients.value.push(newPatient);
        ElMessage.success('添加成功')
    } else {
      ElMessage.error(res.data?.msg || '添加失败')
    }
  }
  modalVisible.value = false
}
function resetModal() {
  editingId.value = null
  modalForm.value = { realName: '', gender: '', birthDate: '', phone: '', idCard: '', address: '', status: 1 }
}
function handleDelete(row: Patient) {
  ElMessageBox.confirm(`确定要删除患者 ${row.realName} 吗？`, '提示', { type: 'warning' })
    .then(() => {
      deletePatientApi(Number(row.id))
      .then(res => {
        if (res && res.code === 200) {
          patients.value = patients.value.filter((p: Patient) => p.id !== row.id)
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(res.data?.msg || '删除失败')
        }
      })
    })
}
function getAge(birthDate: string): number | string {
  if (!birthDate) return '-'
  const birth = new Date(birthDate)
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const m = today.getMonth() - birth.getMonth()
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  return age >= 0 ? age : '-'
}
function handleExport() {
  exportPatientApi()
    .then(res => {
      downloadBlobFile(res, 'patients.xlsx')
      ElMessage.success('导出成功')
    })
    .catch(err => {
      ElMessage.error('导出失败')
    })
}

function goDetail(row: Patient) {
  router.push(`/admin/patient/${row.id}`)
}
// 清空任一搜索框时重新请求第一页
watch([searchRealName, searchPhone], ([val1, val2]) => {
  if (!val1 && !val2) {
    handleSearch()
  }
})
</script>
<style scoped>
.patient-list-page {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 18px;
}

.search-input {
  width: 260px;
}

.pagination {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
}
</style>